/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GameMainPanel.java
 *
 * Created on Aug 28, 2011, 5:30:19 PM
 */
package cw.ui;

import com.jtattoo.plaf.aero.AeroLookAndFeel;
import cw.entity.CrossFields;
import cw.entity.Puzzle;
import cw.entity.Question;
import cw.server.ServerConfig;
import cw.server.ServerInterface;
import cw.ulti.Keyboard;
import cw.ulti.PuzzleUltil;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;

/**
 *
 * @author BAOBAO
 */
public class GameMainPanel extends javax.swing.JFrame {

    static ServerConfig sc = new ServerConfig();//Create instance of ServerConfig
    int _time;
    String keypressed;
    JTextField[][] wo;
    static String[][] cells;
    static String[][] result;
    int posX = -1, posY = -1;
    private static String puzzleName = "";
    int rowSize = 4;
    int colSize = 4;
    PuzzleUltil pul = new PuzzleUltil();
    List<Question> quesList = new ArrayList<Question>();
    Clock clk = new Clock();
    static int timePlay = 0;
    static int levelId = 1, subjectId = 1, sizeId = 1;
    static int correct = 0;
    static int incorrect = 0;
    static int totalResult = 0;
    static String playerName = "player";
    int scoreRate = 3;
    boolean finished = false;
    int questionQuantity, hintQuantity = 0;
    static boolean isPause = false;
    static Puzzle puzzle = new Puzzle();

    /** Creates new form GameMainPanel */
    public GameMainPanel() {
        initComponents();
    }

    public GameMainPanel(int levelId, int subjectId, int sizeId, String playerName) {
        initComponents();
        GameMainPanel.levelId = levelId;
        GameMainPanel.subjectId = subjectId;
        GameMainPanel.sizeId = sizeId;
        GameMainPanel.playerName = playerName;
        jlblHelloPlayer.setText("Hello: "+playerName);
    }

    /**
     * ShowFrame
     * @param obj
     * @param title
     * @throws SecurityException
     */
    public void ShowFrame(JPanel obj, String title) throws SecurityException {
        JDialog frame = new JDialog();
        frame.setContentPane(obj);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setResizable(false);
        frame.setAlwaysOnTop(true);
        frame.setModal(true);
        frame.setTitle(title);
        frame.setLocationByPlatform(true);
        //frame.pack();
        frame.setLocation(500, 200);
        frame.setSize(534, 450);
        frame.setVisible(true);

    }

    /**
     * ShowFrameAbout
     * @param obj
     * @param title
     * @throws SecurityException
     */
    public void ShowFrameAbout(JPanel obj, String title) throws SecurityException {
        JDialog frame = new JDialog();
        frame.setContentPane(obj);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setResizable(false);
        frame.setAlwaysOnTop(true);
        frame.setModal(true);
        frame.setTitle(title);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setLocation(500, 200);

        frame.setSize(381, 210);
        frame.setVisible(true);
    }

    /**
     * fillQuestionList
     * @param qList
     */
    public void fillQuestionList(List<Question> qList) {
        String[] quesLst = new String[qList.size()];
        for (int i = 0; i < qList.size(); i++) {
            quesLst[i] = qList.get(i).getQuestion();
        }
        for (int i = 0; i < qList.size(); i++) {
            jlstQuestionList.setListData(quesLst);
        }
    }

    /**
     * scoreRate
     * @param levelName
     * @return int
     */
    public static int scoreRate(String levelName) {
        if (levelName.equalsIgnoreCase("Easy")) {
            return 1;
        } else if (levelName.equalsIgnoreCase("Normal")) {
            return 2;
        } else if (levelName.equalsIgnoreCase("Hard")) {
            return 3;
        } else if (levelName.equalsIgnoreCase("Expert")) {
            return 4;
        } else {
            return 1;
        }
    }

    /**
     * finishGame
     */
    public void finishGame() {
        finished = true;
        correct = 0;
        incorrect = 0;
        totalResult = 0;
        for (int i = 0; i < cells.length; i++) {
            for (int j = 0; j < cells[i].length; j++) {
                System.out.println("Answer(" + i + ", " + j + ")" + cells[i][j]);
                System.out.println("Result(" + i + ", " + j + ")" + result[i][j]);
                for (int k = 0; k < result.length; k++) {
                    for (int l = 0; l < result[k].length; l++) {
                        if (k == i && l == j) {

                            if (cells[i][j] != null && result[k][l] != null && !cells[i][j].equals("*") && !result[k][l].equals("*")) {
                                
                                if (cells[i][j].equalsIgnoreCase(result[k][l])) {
                                    correct++;
                                }
                            }
                            if (result[k][l] != null && !result[k][l].equals("*")) {
                                totalResult++;
                            }
                        }
                    }
                }
            }
        }
        incorrect = totalResult - correct;
        clk.stop();
        jbtnPauseGame.setEnabled(false);
        jbtnPlayGame.setEnabled(false);
        jbtnFinishGame.setEnabled(false);
        char[][] cellChangeBackground = new char[2][2];
        generatePuzzle(rowSize, colSize, cellChangeBackground, result, true, true);

        int score = scoreRate * correct;
        jlblLastScore.setText("Correct: " + correct + " (" + String.valueOf(score) + " point)");
        System.out.println("Incorrect: " + incorrect);
        if (incorrect == 0) {
            ShowFrame(new ConfirmPlayerProfile(playerName, puzzle.getPuzzleId(), score, clk.timeOver), "Cross Words - Save score");
        } else {
            JOptionPane.showMessageDialog(this, "Sorry!!! You lost - lets try again");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jbtnNewGame = new javax.swing.JButton();
        jbtnHightScores = new javax.swing.JButton();
        jbtnHistory = new javax.swing.JButton();
        jbtnExit = new javax.swing.JButton();
        jbtnHelp = new javax.swing.JButton();
        jbtnPlayGame = new javax.swing.JButton();
        jbtnPauseGame = new javax.swing.JButton();
        jbtnFinishGame = new javax.swing.JButton();
        lblHint = new javax.swing.JLabel();
        jtxtCaption = new javax.swing.JTextField();
        jlblHelloPlayer = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jlblLastScore = new javax.swing.JLabel();
        lblTimer = new javax.swing.JLabel();
        jlblVisitWebsite = new javax.swing.JLabel();
        jscpPuzzleInterface = new javax.swing.JScrollPane();
        jpnPuzzleInterface = new javax.swing.JPanel();
        jlblLoading = new javax.swing.JLabel();
        jlblHintAnswer = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlstQuestionList = new javax.swing.JList();
        jlblShowIntructorHint = new javax.swing.JLabel();
        lblBackground = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cross Words 2011");
        setMinimumSize(new java.awt.Dimension(850, 675));
        setResizable(false);

        jPanel1.setLayout(null);

        jbtnNewGame.setFont(new java.awt.Font("Arial", 1, 11));
        jbtnNewGame.setForeground(new java.awt.Color(255, 255, 255));
        jbtnNewGame.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/play.png"))); // NOI18N
        jbtnNewGame.setText(" New Game");
        jbtnNewGame.setBorder(null);
        jbtnNewGame.setBorderPainted(false);
        jbtnNewGame.setContentAreaFilled(false);
        jbtnNewGame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNewGameActionPerformed(evt);
            }
        });
        jPanel1.add(jbtnNewGame);
        jbtnNewGame.setBounds(280, 40, 100, 33);

        jbtnHightScores.setFont(new java.awt.Font("Arial", 1, 11));
        jbtnHightScores.setForeground(new java.awt.Color(255, 255, 255));
        jbtnHightScores.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/hightscore.png"))); // NOI18N
        jbtnHightScores.setText("Hight Scores");
        jbtnHightScores.setBorder(null);
        jbtnHightScores.setBorderPainted(false);
        jbtnHightScores.setContentAreaFilled(false);
        jbtnHightScores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnHightScoresActionPerformed(evt);
            }
        });
        jPanel1.add(jbtnHightScores);
        jbtnHightScores.setBounds(400, 40, 110, 33);

        jbtnHistory.setFont(new java.awt.Font("Arial", 1, 11));
        jbtnHistory.setForeground(new java.awt.Color(255, 255, 255));
        jbtnHistory.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/history.png"))); // NOI18N
        jbtnHistory.setText("About");
        jbtnHistory.setBorder(null);
        jbtnHistory.setBorderPainted(false);
        jbtnHistory.setContentAreaFilled(false);
        jbtnHistory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnHistoryActionPerformed(evt);
            }
        });
        jPanel1.add(jbtnHistory);
        jbtnHistory.setBounds(520, 40, 90, 33);

        jbtnExit.setFont(new java.awt.Font("Arial", 1, 11));
        jbtnExit.setForeground(new java.awt.Color(255, 255, 255));
        jbtnExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exit.png"))); // NOI18N
        jbtnExit.setText("Quit");
        jbtnExit.setBorder(null);
        jbtnExit.setBorderPainted(false);
        jbtnExit.setContentAreaFilled(false);
        jbtnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExitActionPerformed(evt);
            }
        });
        jPanel1.add(jbtnExit);
        jbtnExit.setBounds(740, 40, 70, 33);

        jbtnHelp.setFont(new java.awt.Font("Arial", 1, 11));
        jbtnHelp.setForeground(new java.awt.Color(255, 255, 255));
        jbtnHelp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help_32.png"))); // NOI18N
        jbtnHelp.setText(" Help");
        jbtnHelp.setBorder(null);
        jbtnHelp.setBorderPainted(false);
        jbtnHelp.setContentAreaFilled(false);
        jbtnHelp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnHelpActionPerformed(evt);
            }
        });
        jPanel1.add(jbtnHelp);
        jbtnHelp.setBounds(640, 40, 70, 33);

        jbtnPlayGame.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/continue.png"))); // NOI18N
        jbtnPlayGame.setText("Start");
        jbtnPlayGame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnPlayGameActionPerformed(evt);
            }
        });
        jPanel1.add(jbtnPlayGame);
        jbtnPlayGame.setBounds(250, 580, 90, 30);

        jbtnPauseGame.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/pause.png"))); // NOI18N
        jbtnPauseGame.setText("Pause");
        jbtnPauseGame.setEnabled(false);
        jbtnPauseGame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnPauseGameActionPerformed(evt);
            }
        });
        jPanel1.add(jbtnPauseGame);
        jbtnPauseGame.setBounds(140, 580, 100, 30);

        jbtnFinishGame.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/finishe.png"))); // NOI18N
        jbtnFinishGame.setText(" Finish Game");
        jbtnFinishGame.setEnabled(false);
        jbtnFinishGame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnFinishGameActionPerformed(evt);
            }
        });
        jPanel1.add(jbtnFinishGame);
        jbtnFinishGame.setBounds(350, 580, 120, 30);

        lblHint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/export16.png"))); // NOI18N
        lblHint.setText("Question:");
        jPanel1.add(lblHint);
        lblHint.setBounds(50, 120, 110, 30);

        jtxtCaption.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.add(jtxtCaption);
        jtxtCaption.setBounds(50, 150, 420, 30);

        jlblHelloPlayer.setFont(new java.awt.Font("Arial", 1, 12));
        jlblHelloPlayer.setForeground(new java.awt.Color(0, 0, 204));
        jlblHelloPlayer.setText("Hello: Player");
        jPanel1.add(jlblHelloPlayer);
        jlblHelloPlayer.setBounds(520, 570, 90, 20);

        jLabel1.setFont(new java.awt.Font("Tahoma", 2, 12));
        jLabel1.setForeground(new java.awt.Color(0, 0, 204));
        jLabel1.setText("Last score: ");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(520, 600, 80, 15);

        jlblLastScore.setFont(new java.awt.Font("Tahoma", 0, 12));
        jlblLastScore.setForeground(new java.awt.Color(255, 153, 0));
        jlblLastScore.setText("N/A");
        jPanel1.add(jlblLastScore);
        jlblLastScore.setBounds(600, 600, 220, 15);

        lblTimer.setFont(new java.awt.Font("Arial", 1, 14));
        lblTimer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/timer.png"))); // NOI18N
        lblTimer.setText(" 00:00");
        jPanel1.add(lblTimer);
        lblTimer.setBounds(290, 528, 180, 32);

        jlblVisitWebsite.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jlblVisitWebsiteMouseClicked(evt);
            }
        });
        jPanel1.add(jlblVisitWebsite);
        jlblVisitWebsite.setBounds(50, 0, 200, 70);

        jpnPuzzleInterface.setBackground(new java.awt.Color(255, 255, 255));

        jlblLoading.setBackground(new java.awt.Color(255, 255, 255));
        jlblLoading.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/puzzle3.jpg"))); // NOI18N
        jlblLoading.setPreferredSize(new java.awt.Dimension(24, 24));

        javax.swing.GroupLayout jpnPuzzleInterfaceLayout = new javax.swing.GroupLayout(jpnPuzzleInterface);
        jpnPuzzleInterface.setLayout(jpnPuzzleInterfaceLayout);
        jpnPuzzleInterfaceLayout.setHorizontalGroup(
            jpnPuzzleInterfaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnPuzzleInterfaceLayout.createSequentialGroup()
                .addGap(59, 59, 59)
                .addComponent(jlblLoading, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(60, Short.MAX_VALUE))
        );
        jpnPuzzleInterfaceLayout.setVerticalGroup(
            jpnPuzzleInterfaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnPuzzleInterfaceLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jlblLoading, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(20, Short.MAX_VALUE))
        );

        jscpPuzzleInterface.setViewportView(jpnPuzzleInterface);

        jPanel1.add(jscpPuzzleInterface);
        jscpPuzzleInterface.setBounds(50, 200, 420, 310);

        jlblHintAnswer.setEnabled(false);
        jlblHintAnswer.setToolTipText("Click here to get hint");
        jlblHintAnswer.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jlblHintAnswer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jlblHintAnswerMouseReleased(evt);
            }
        });
        jPanel1.add(jlblHintAnswer);
        jlblHintAnswer.setBounds(40, 560, 90, 80);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Questions list of puzzle"));

        jlstQuestionList.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jlstQuestionList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jlstQuestionListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jlstQuestionList);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel1.add(jPanel2);
        jPanel2.setBounds(510, 210, 310, 340);

        jlblShowIntructorHint.setVisible(false);
        jlblShowIntructorHint.setForeground(new java.awt.Color(0, 51, 255));
        jlblShowIntructorHint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/hint.png"))); // NOI18N
        jlblShowIntructorHint.setText("Click below games logo to get hint");
        jPanel1.add(jlblShowIntructorHint);
        jlblShowIntructorHint.setBounds(50, 520, 230, 30);

        lblBackground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/userMain.png"))); // NOI18N
        jPanel1.add(lblBackground);
        lblBackground.setBounds(0, 0, 860, 691);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 850, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE)
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-866)/2, (screenSize.height-713)/2, 866, 713);
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExitActionPerformed
        int index = JOptionPane.showConfirmDialog(jbtnExit, "Are you sure want to quit game?", "Confirm for quit game", JOptionPane.YES_NO_OPTION);
        if (index == 0) {
            System.exit(0);
        }
    }//GEN-LAST:event_jbtnExitActionPerformed

    private void jbtnHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnHelpActionPerformed
        try {
            Desktop.getDesktop().open(new File("src/Docs/UserGuide.chm"));
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "User guide is not available");
        }
    }//GEN-LAST:event_jbtnHelpActionPerformed

    private void jlblHintAnswerMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jlblHintAnswerMouseReleased
        try {
            ServerInterface stub = sc.Setup();
            hintQuantity++;
            if (hintQuantity <= questionQuantity) {
                String questContent = jlstQuestionList.getSelectedValue().toString().trim();

                Question quest = null;
                try {
                    quest = stub.getQuestionByQuestionContent(questContent);
                } catch (Exception e) {
                    jtxtCaption.setText(questContent);
                }
                if (quest != null) {
                    String answ = quest.getAnswer();
                    jtxtCaption.setText("Answer of this question is start with: " + answ.substring(0, 1));
                    jtxtCaption.setForeground(Color.red);
                }
            } else {
                jlblShowIntructorHint.setText("You haven't got any hint");
            }

        } catch (Exception ex) {
            Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jlblHintAnswerMouseReleased

    private void jbtnFinishGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnFinishGameActionPerformed
        finishGame();
    }//GEN-LAST:event_jbtnFinishGameActionPerformed

    private void jlstQuestionListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jlstQuestionListValueChanged
        try {
            ServerInterface stub = sc.Setup();
            String questContent = jlstQuestionList.getSelectedValue().toString().trim();
            jtxtCaption.setForeground(Color.BLACK);
            Question quest = null;
            try {
                quest = stub.getQuestionByQuestionContent(questContent);
            } catch (Exception e) {
                jtxtCaption.setText(questContent);
            }
            if (quest != null) {
                int psX = quest.getPositionX();
                int psY = quest.getPositionY();
                boolean direction = quest.getDirection();
                String answ = quest.getAnswer();
                jtxtCaption.setText(questContent + " (" + answ.length() + " words)");

                if (!finished) {
                    char[][] cellChangeBackground = new char[rowSize][colSize];
                    cellChangeBackground = pul.getCellsByPosisitonAndDirection(rowSize, colSize, psX, psY, answ, direction);

                    generatePuzzle(rowSize, colSize, cellChangeBackground, result, true, false);
                } else {
                    jtxtCaption.setText("Answer: " + quest.getAnswer());
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jlstQuestionListValueChanged

    private void jlblVisitWebsiteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jlblVisitWebsiteMouseClicked
        PuzzleUltil.openURL("http://www.crossword-puzzles.co.uk/");
    }//GEN-LAST:event_jlblVisitWebsiteMouseClicked

    private void jbtnPlayGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnPlayGameActionPerformed
        try {
            timePlay = 0;
            ServerInterface stub = sc.Setup();
            cells = new String[rowSize][colSize];
            jlstQuestionList.setVisible(true);
            char[][] cellChangeBackground = new char[2][2];
            jpnPuzzleInterface.removeAll();

            jbtnFinishGame.setEnabled(true);
            jbtnPauseGame.setEnabled(true);
            jbtnPlayGame.setEnabled(false);

            String levelName = null;
//            levelId = 1;
//            sizeId = 1;
//            subjectId = 1;
            System.out.println("level:" + levelId + ", sizeId: " + sizeId + ", subjId: " + subjectId);
            try {
                try {
                    puzzle = stub.getPuzzleRandom(levelId, sizeId, subjectId);
                } catch (Exception e) {
                    Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, e);
                }
                System.out.println("puzzleName: " + puzzle.getPuzzleName());
                try {
                    System.out.println("levelName: " + puzzle.getLevel().getLevelName());
                    timePlay = puzzle.getLevel().getCountDown();
                } catch (Exception e) {
                    int loop = 0;
                    while (timePlay == 0 && loop < 10) {
                        try {
                            loop++;
                            timePlay = puzzle.getLevel().getCountDown();
                        } catch (Exception ex1) {
                            Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, ex1);
                        }
                    }
                    Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, e);
                } finally {
                    timePlay = 120;
                }
                try {
                    levelName = puzzle.getLevel().getLevelName();
                    scoreRate = scoreRate(levelName);
                } catch (Exception e) {
                    int loop = 0;
                    while (levelName == null && loop < 10) {
                        try {
                            loop++;
                            levelName = puzzle.getLevel().getLevelName();
                            scoreRate = scoreRate(levelName);
                        } catch (Exception ex3) {
                            Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, ex3);
                        }
                    }
                    Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, e);
                } finally {
                    scoreRate = 1;
                }

                clk.start();
                List<Question> qList = null;
                try {
                    qList = stub.getQuestionByPuzzleId(puzzle.getPuzzleId());
                } catch (Exception e) {
                    qList = stub.getQuestionByPuzzleId(2);
                    Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, e);
                }

                questionQuantity = qList.size();
                System.out.println("quest quantity: " + qList.size());
                result = pul.getCellsOfPuzzleFromDatabase(qList, rowSize, colSize);
                fillQuestionList(qList);
                generatePuzzle(4, 4, cellChangeBackground, result, true, false);
            } catch (Exception e) {
                Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, e);
                int option = JOptionPane.showConfirmDialog(this, "Error connection!!! Do you want to refress connection to server? ", "Error connection", JOptionPane.YES_NO_OPTION);
                if (option == 0) {
                    Thread thread = new Thread(new Runnable() {

                        public void run() {
                            GameMainPanel gmp = new GameMainPanel();
                            gmp.setVisible(true);
                        }
                    });
                    thread.start();
                    this.dispose();
                } else {
                    PlayerSettingGame newGame = new PlayerSettingGame();
                    newGame.setVisible(true);
                    this.dispose();
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jbtnPlayGameActionPerformed

    private void jbtnHistoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnHistoryActionPerformed
        ShowFrameAbout(new About(), "Cross Words - About us");
    }//GEN-LAST:event_jbtnHistoryActionPerformed

    private void jbtnNewGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNewGameActionPerformed
        int choise = (JOptionPane.showConfirmDialog(null, "Are you sure want to create new game?", "Are you sure create new game?", JOptionPane.YES_NO_OPTION));
        if (choise == 0) {
            //Show setting game frame
            PlayerSettingGame newGame = new PlayerSettingGame();
            newGame.setVisible(true);
            this.dispose();
        } else {
            //do nothing
        }
    }//GEN-LAST:event_jbtnNewGameActionPerformed

    private void jbtnPauseGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnPauseGameActionPerformed
        if (!isPause) {
            try {
//                Thread.currentThread().interrupt();
                clk.suspend();
                jbtnPauseGame.setText("Resume");
                isPause = true;
                jtxtCaption.setVisible(false);
                jscpPuzzleInterface.setVisible(false);
                jlstQuestionList.setVisible(false);
            } catch (Exception ex) {
                Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            clk.resume();
            jbtnPauseGame.setText("Pause");
            isPause = false;
            jtxtCaption.setVisible(true);
            jlstQuestionList.setVisible(true);
            jscpPuzzleInterface.setVisible(true);
        }
    }//GEN-LAST:event_jbtnPauseGameActionPerformed

    private void jbtnHightScoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnHightScoresActionPerformed
        ShowFrame(new HighScores(), "Cross Words - High Score");
    }//GEN-LAST:event_jbtnHightScoresActionPerformed

    /**
     * set_time of clock
     */
    public class Clock extends Thread {

        int timeOver = 0;
        boolean pleaseWait = false;

        public Clock() {
        }

        @Override
        public void run() {
            int p = timePlay;

            int m = p / 60;
            int s = p - 60 * m;
            int kk = 0;
            for (int i = p; i >= 0; i--) {
                _time = i;
                kk++;
                final int ii = kk;
                final int mm = m;
                final int ss = s;
                try {
                    SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            if (mm < 10) {
                                if (ss < 10) {
                                    update_timer("0" + mm + " : " + "0" + ss, mm, ss);
                                } else {
                                    update_timer("0" + mm + " : " + ss, mm, ss);
                                }
                            } else {
                                if (ss < 10) {
                                    update_timer(mm + " : " + "0" + ss, mm, ss);
                                } else {
                                    update_timer(mm + " : " + ss, mm, ss);
                                }
                            }
                        }
                    });
                    java.lang.Thread.sleep(1000);
                    timeOver++;
                    if (timeOver % 5 == 0) {
                        jlblHintAnswer.setEnabled(true);
                        jlblShowIntructorHint.setVisible(true);
                    }
                    if (timeOver % 10 == 0) {
                        jlblShowIntructorHint.setVisible(false);
                    }
                } catch (InterruptedException e) {
                }
                if (m == 0 && s == 0) {
                    lblTimer.setText("Times over");
                    lblTimer.setForeground(Color.red);
                    Clock cl = new Clock();
                    cl.finishGame();
                }
                if (s == 0) {
                    m--;
                    s = 60;
                }
                s--;
            }
        }

        public void finishGame() {
            try {
                finished = true;
                correct = 0;
                incorrect = 0;
                totalResult = 0;
                for (int i = 0; i < cells.length; i++) {
                    for (int j = 0; j < cells[i].length; j++) {
                        System.out.println("Answer(" + i + ", " + j + ")" + cells[i][j]);
                        System.out.println("Result(" + i + ", " + j + ")" + result[i][j]);
                        for (int k = 0; k < result.length; k++) {
                            for (int l = 0; l < result[k].length; l++) {
                                if (k == i && l == j) {
                                    if (cells[i][j] != null && result[k][l] != null && !cells[i][j].equals("*") && !result[k][l].equals("*")) {
                                        totalResult++;
                                        if (cells[i][j].equalsIgnoreCase(result[k][l])) {
                                            correct++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                incorrect = totalResult - correct;
//                clk.stop();
                jbtnPauseGame.setEnabled(false);
                jbtnPlayGame.setEnabled(false);
                jbtnFinishGame.setEnabled(false);
                char[][] cellChangeBackground = new char[2][2];
                generatePuzzle(rowSize, colSize, cellChangeBackground, result, true, true);

                int score = scoreRate * correct;
                jlblLastScore.setText("Correct: " + correct + " (" + String.valueOf(score) + " point)");
                System.out.println("Incorrect: " + incorrect);
                if (incorrect == 0) {
                    ShowFrame(new ConfirmPlayerProfile(playerName, puzzle.getPuzzleId(), score, clk.timeOver), "Cross Words - Save score");
                } else {
                    JOptionPane.showMessageDialog(null, "Sorry!!! You lost - lets try again");
                }
            } catch (Exception e) {
                Logger.getLogger(GameMainPanel.class.getName()).log(Level.SEVERE, null, e);
            }
        }
    }

    /**
     * update_timer
     * @param text
     * @param mm
     * @param ss
     */
    public void update_timer(String text, int mm, int ss) {
        lblTimer.setText(text);
        if (mm < 1) {
            lblTimer.setForeground(Color.red);

        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
//                    UIManager.setLookAndFeel(new McWinLookAndFeel());
//                    UIManager.setLookAndFeel(new LunaLookAndFeel());
//                    UIManager.setLookAndFeel(new AcrylLookAndFeel());
//                    UIManager.setLookAndFeel(new AluminiumLookAndFeel());
                    UIManager.setLookAndFeel(new AeroLookAndFeel());
                    GameMainPanel gamePanel = new GameMainPanel();
                    gamePanel.setVisible(true);
                    gamePanel.jlstQuestionList.setVisible(false);

//                    char[][] cellChangeBackground = new char[2][2];
//                    gamePanel.generatePuzzle(4, 4, cellChangeBackground, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * generatePuzzle
     * @param rowSize
     * @param colSize
     * @param cellChangeBackground
     * @param cellResult
     * @param status
     * @param isFinish - if finish to display result all cells
     */
    private void generatePuzzle(final int rowSize, int colSize, char[][] cellChangeBackground, String[][] cellResult, boolean status, boolean isFinish) {

        jpnPuzzleInterface = new JPanel(new GridLayout(rowSize, colSize, 3, 3));
        wo = new JTextField[rowSize][colSize];
        //Loop for generate cell of puzzle
        for (int i = 0; i < rowSize; i++) {
            for (int j = 0; j < colSize; j++) {
                wo[i][j] = new CrossFields(i, j);
                wo[i][j].setFont(new java.awt.Font("Arial", 1, 20));
                //Loop for change background of row or column contain question player choosing
                for (int k = 0; k < cellChangeBackground.length; k++) {
                    for (int l = 0; l < cellChangeBackground[k].length; l++) {
                        //Check position to change background color
                        if (!String.valueOf(cellChangeBackground[k][l]).trim().isEmpty() && !String.valueOf(cellChangeBackground[k][l]).trim().equals("")) {
                            if (k == i && l == j) {
                                wo[i][j].setBackground(new Color(255, 255, 210));
                            }
                        }
                    }
                }
                wo[i][j].setToolTipText("Lets enter a character");
                for (int k = 0; k < cellResult.length; k++) {
//                    System.out.println("maxk=" + cellResult.length);
                    for (int l = 0; l < cellResult[k].length; l++) {
//                        System.out.println("maxl=" + cellResult[k].length);
                        //Check position to change background color
                        if (cellResult[k][l] == null) {
                            if (k == i && l == j) {
                                wo[i][j].setText("*");
                                wo[i][j].setEditable(false);
                                wo[i][j].setForeground(Color.YELLOW);
                                wo[i][j].setToolTipText("You cannot edit this cell");
                            }
                        }
                        if (isFinish) {
                            if (cellResult[k][l] != null) {
                                if (k == i && l == j) {
                                    wo[i][j].setText(cellResult[k][l]);
                                    wo[i][j].setEditable(false);

                                    wo[i][j].setToolTipText("");

                                    if (cells[i][j] != null) {
                                        if (cells[i][j].equalsIgnoreCase(cellResult[k][l].trim()) && !cellResult[k][l].trim().equalsIgnoreCase("*")) {
                                            //Change background of correct words to green color
                                            wo[i][j].setBackground(new Color(138, 243, 145));
                                        } else {
                                            //Change background of correct words to red color
                                            wo[i][j].setBackground(new Color(252, 183, 171));
                                        }
                                    } else {
                                        wo[i][j].setBackground(new Color(252, 183, 171));
                                    }
                                }
                            }
                        }
                    }
                }

                wo[i][j].setEnabled(status);
                //Check if cells is not empty then disable cells
                if (cells != null && cells.length > 0) {
                    for (int k = 0; k < cells.length; k++) {
                        for (int l = 0; l < cells[k].length; l++) {
                            if (cells[k][l] != null && !cells[k][l].trim().equals("")) {
                                if (i == k && j == l) {
//                                    System.out.println("Position 1: ("+i+", "+j+")");
//                                    System.out.println("cell (" + k + ", " + l + ")" + cells[k][l]);
//                                    wo[i][j].setBackground(Color.red);
                                    wo[i][j].setText(cells[k][l].toUpperCase());
                                }
                            }
                        }
                    }
                }
                //Set attribute for text box - Cell of Puzzle

                wo[i][j].setForeground(new Color(102, 0, 0));
                wo[i][j].setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
                wo[i][j].setHorizontalAlignment(SwingConstants.CENTER);
//                wo[i][j].setEnabled(status);

                wo[i][j].addMouseListener(new MouseAdapter() {

                    @Override
                    public void mousePressed(MouseEvent e) {
                        CrossFields cell = (CrossFields) e.getSource();

                        //Display virtual keyboard when righ mouse clicked
                        if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
                            DisplayKeyboard();
                            Keyboard panel = new Keyboard();
                            keypressed = panel.getKeyPressed();
                            cell.setText(keypressed.toUpperCase());
                        }
                        posX = cell.getPoX();
                        posY = cell.getPoY();
                        cells[posX][posY] = keypressed;
                    }
                }); //Add key listener for get character of palayer inputed
                wo[i][j].addKeyListener(new KeyAdapter() {

                    @Override
                    public void keyReleased(KeyEvent e) {
                        try {
                            CrossFields cell = (CrossFields) e.getSource();
//                            e.setKeyChar(String.valueOf(e.getKeyChar()).toUpperCase().charAt(0));
                            String charinput = ((JTextField) e.getSource()).getText().trim().substring(0, 1).toUpperCase();
                            ((JTextField) e.getSource()).setText(charinput.toUpperCase());
                            posX = cell.getPoX();
                            posY = cell.getPoY();
                            cells[posX][posY] = charinput.toUpperCase();
                        } catch (Exception ex) {
//                            e.setKeyChar(e.getKeyChar());
                        }
                    }
                });
                jpnPuzzleInterface.add(wo[i][j]);
            }
        }

        jscpPuzzleInterface.setViewportView(jpnPuzzleInterface);
    }

    /**
     * DisplayKeyboard
     * @throws HeadlessException
     */
    public void DisplayKeyboard() throws HeadlessException {
        JDialog frame = new JDialog();
        Keyboard panel = new Keyboard();
//        frame.setContentPane(panel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setResizable(false);
        frame.setModal(true);
        frame.setTitle("Cross-Words Virtual keyboard");
        frame.setForeground(Color.white);
        frame.setBackground(Color.lightGray);
        frame.getContentPane().add(panel, "Center");
//        frame.getContentPane().add(panel);
        panel.key();

        frame.pack();
        frame.setSize(300, 140);
        Point location = MouseInfo.getPointerInfo().getLocation();
        int x = (int) location.getX();
        int y = (int) location.getY();
        frame.setLocation(x, y);
        frame.setVisible(true);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtnExit;
    private javax.swing.JButton jbtnFinishGame;
    private javax.swing.JButton jbtnHelp;
    private javax.swing.JButton jbtnHightScores;
    private javax.swing.JButton jbtnHistory;
    private javax.swing.JButton jbtnNewGame;
    private javax.swing.JButton jbtnPauseGame;
    private javax.swing.JButton jbtnPlayGame;
    private javax.swing.JLabel jlblHelloPlayer;
    private javax.swing.JLabel jlblHintAnswer;
    private javax.swing.JLabel jlblLastScore;
    private javax.swing.JLabel jlblLoading;
    private javax.swing.JLabel jlblShowIntructorHint;
    private javax.swing.JLabel jlblVisitWebsite;
    private javax.swing.JList jlstQuestionList;
    private javax.swing.JPanel jpnPuzzleInterface;
    private javax.swing.JScrollPane jscpPuzzleInterface;
    private javax.swing.JTextField jtxtCaption;
    private javax.swing.JLabel lblBackground;
    private javax.swing.JLabel lblHint;
    private javax.swing.JLabel lblTimer;
    // End of variables declaration//GEN-END:variables
}
